package parser;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectInputStream.GetField;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import data.RTEData;
import data.RTENode;
import data.RTEPreprocessedData;
import data.RTESentence;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class RTEXmlParser {
	
	public static void readPreprocessedData() {
		try {
	        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	        File file = new File("datasets//RTE2_dev.preprocessed.xml");
	        Document doc = docBuilder.parse (file);
	        
	        NodeList pairList = doc.getElementsByTagName("pair");

	        //iterate over pairs
	        for(int i = 0; i < pairList.getLength(); i++) {
	        	Node currentNode = pairList.item(i);
	        	NamedNodeMap attributes = currentNode.getAttributes();
	        	
	        	boolean entailment = (attributes.getNamedItem("entailment").getNodeValue().toLowerCase().equals("yes") ? true : false);
	        	int id = Integer.parseInt(attributes.getNamedItem("id").getNodeValue());
	       
	        	NodeList textList = ((Element)currentNode).getElementsByTagName("text");
	        	NodeList textSentences =  ((Element)textList.item(0)).getElementsByTagName("sentence");
	        	
	        	ArrayList<RTESentence> text = new ArrayList<RTESentence>();
	        	//iterate over all text sentences
	        	for(int k = 0; k < textSentences.getLength(); k++) {
	        		Element element = (Element)textSentences.item(k);
	        		NodeList sentenceNodes = element.getElementsByTagName("node");
	        		
	        		ArrayList<RTENode> textNodes = new ArrayList<RTENode>();
		        	for (int j = 0; j < sentenceNodes.getLength(); j++) {
		        		Element nodeElement = (Element)sentenceNodes.item(j);
		        		
		        		String nodeId = sentenceNodes.item(j).getAttributes().getNamedItem("id").getTextContent();     		
		        		Node word = nodeElement.getElementsByTagName("word").item(0);
		        		Node lemma = nodeElement.getElementsByTagName("lemma").item(0);
		        		Node posTag = nodeElement.getElementsByTagName("pos-tag").item(0);
		        		Node relation = nodeElement.getElementsByTagName("relation").item(0);
		        		Node antecendent = nodeElement.getElementsByTagName("antecendent").item(0);
		        		
		        		textNodes.add(new RTENode(nodeId, word, lemma, posTag, relation, antecendent));
	        		}
	             	text.add(new RTESentence(textNodes));
	        	}
	        	
	        	NodeList hypList = ((Element)currentNode).getElementsByTagName("hypothesis");
	           	NodeList hypSentences = ((Element)hypList.item(0)).getElementsByTagName("sentence");
	        	
	           	ArrayList<RTESentence> hypothesis = new ArrayList<RTESentence>();
	        	
	        	//iterate over all hypothesis sentences
	        	for(int k = 0; k < hypSentences.getLength(); k++) {
	        		Element element = (Element)hypSentences.item(k);
	        		NodeList sentenceNodes = element.getElementsByTagName("node");
	        		
	               	ArrayList<RTENode> hypNodes = new ArrayList<RTENode>();
                  	for (int j = 0; j < sentenceNodes.getLength(); j++) {
		        		Element nodeElement = (Element)sentenceNodes.item(j);
		        		
		        		String nodeId = sentenceNodes.item(j).getAttributes().getNamedItem("id").getTextContent();     		
		        		Node word = nodeElement.getElementsByTagName("word").item(0);
		        		Node lemma = nodeElement.getElementsByTagName("lemma").item(0);
		        		Node posTag = nodeElement.getElementsByTagName("pos-tag").item(0);
		        		Node relation = nodeElement.getElementsByTagName("relation").item(0);
		        		Node antecendent = nodeElement.getElementsByTagName("antecendent").item(0);
		        		
		        		hypNodes.add(new RTENode(nodeId, word, lemma, posTag, relation, antecendent));
	        		}
	             	hypothesis.add(new RTESentence(hypNodes));
	        	}
	        	new RTEPreprocessedData(id, entailment, text, hypothesis);        	
	        }
		} catch(ParserConfigurationException pex) {
			pex.printStackTrace();
		} catch(IOException iex) {
			iex.printStackTrace();
		} catch(SAXException saex) {
			saex.printStackTrace();
		}
	}
	
	public static void readData() {

		try {
	        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
	        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
	        File file = new File("datasets//RTE2_dev.xml");
	        Document doc = docBuilder.parse (file);
	        
	        NodeList pairList = doc.getElementsByTagName("pair");

	        //iterate over pairs
	        for(int i = 0; i < pairList.getLength(); i++) {
	        	Node currentNode = pairList.item(i);
	        	NamedNodeMap attributes = currentNode.getAttributes();
	        	
	        	Node entailmentNode = attributes.getNamedItem("entailment");
	        	
	        	boolean entailment = (entailmentNode.getNodeValue().toLowerCase().equals("yes") ? true : false);
	        	int id = Integer.parseInt(attributes.getNamedItem("id").getNodeValue());
	        
	        	Element currentElement = (Element)currentNode;	
	        	NodeList hypList = currentElement.getElementsByTagName("h");
	        	NodeList textList = currentElement.getElementsByTagName("t");

	        	new RTEData(textList.item(0).getTextContent().toLowerCase(), hypList.item(0).getTextContent().toLowerCase(), id, entailment);	
	        }
	        
		} catch(ParserConfigurationException pex) {
			pex.printStackTrace();
		} catch(IOException iex) {
			iex.printStackTrace();
		} catch(SAXException saex) {
			saex.printStackTrace();
		}
	}
	
	/**
	 * Writes a text-file with the predictions generated from a RTE system
	 * @param className the name of the class which created the output
	 */
	public static void WritePredictions(String className, HashMap<Integer, String> results) {
		String filename = "output//"  + className + "-" + now("yyyy-MM-dd-kk.mm.ss") + ".txt";
		try {
			File file = new File(filename);

			BufferedWriter writer = new BufferedWriter(new FileWriter(file));
			writer.write("ranked: no");

			for(int key : results.keySet()) {
				writer.write("\n" + key + " " + results.get(key));
			}
			
			writer.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static String now(String dateFormat) {
		    Calendar cal = Calendar.getInstance();
		    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		    return sdf.format(cal.getTime());
	}
	
	public static void main(String[] args) {
		readPreprocessedData();
	}
}
